package com.devin.imagepicker;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PermissionHelper;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by apple on 2016/12/6.
 */

public class ImagePickPlugin extends CordovaPlugin {
    public static String TAG = "ImagePickerPlugin";
    public static int REQUEST_CODE = 10000;

    private CallbackContext callbackContext;
    private JSONObject params;

    private ImagePicker imagePicker;

    private Intent intent;

    @Override
    public void onStart() {
        super.onStart();
        imagePicker = ImagePicker.getInstance();
    }

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {

        this.callbackContext = callbackContext;
        this.params = args.getJSONObject(0);
        if (action.equals("getPictures")) {
            intent = new Intent(cordova.getActivity(), ImageGridActivity.class);

            int max = 20;
            if (this.params.has("maxImages")) {
                max = this.params.getInt("maxImages");
            }

            imagePicker.setShowCamera(false);
            imagePicker.setImageLoader(new GlideImageLoader());
            imagePicker.setCrop(false);
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(max);

            try{
                boolean getAlbumPermission = PermissionHelper.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
                if(getAlbumPermission){
                    if (this.cordova != null) {
                        this.cordova.startActivityForResult((CordovaPlugin) this, intent, REQUEST_CODE);
                    }
                }else{
                    PermissionHelper.requestPermission(this, 0, Manifest.permission.READ_EXTERNAL_STORAGE);
                }
            } catch (IllegalArgumentException e) {
                PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
                r.setKeepCallback(true);
                this.callbackContext.sendPluginResult(r);
                return true;
            }
            PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
            r.setKeepCallback(true);
            this.callbackContext.sendPluginResult(r);
            return true;
        }
        return true;
    }

    public void onRequestPermissionResult(int requestCode, String[] permissions,
                                          int[] grantResults) throws JSONException {
        boolean permissionAuth = true ;
        for(int r:grantResults)
        {
            if(r == PackageManager.PERMISSION_DENIED)
            {
                this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, 20));
                permissionAuth = false ;
                break;
            }
        }
        if(permissionAuth){
            switch(requestCode) {
                case 0:
                    if (this.cordova != null) {
                        this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
                    }
                    break;
            }
        }else {
            if (Build.VERSION.SDK_INT >= 23){
                switch (requestCode) {
                    case 0:
                        if(!cordova.getActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)){
                            AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity());
                            builder.setCancelable(false);
                            builder.setTitle("权限申请");
                            builder.setMessage("在设置-应用-"+getApplicationName()+"-权限中开启文件访问权限,以正常使用获取相册列表,选取相片等功能");
                            builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", cordova.getActivity().getPackageName(), null);
                                    intent.setData(uri);
                                    cordova.getActivity().startActivity(intent);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                            AlertDialog alert = builder.create();
                            alert.show();
                        }
                        break;
                }
            }
        }
    }

    public String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = cordova.getActivity().getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(cordova.getActivity().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName =
                (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_CODE) {
            return;
        }

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            ArrayList<String> fileNames = new ArrayList<String>();
            if (images != null) {
                for (ImageItem imageItem : images) {
                    fileNames.add(imageItem.path);
                }
            }
            JSONArray res = new JSONArray(fileNames);
            this.callbackContext.success(res);
        } else if (resultCode == Activity.RESULT_CANCELED && data != null) {
            String error = data.getStringExtra("ERRORMESSAGE");
            this.callbackContext.error(error);
        } else if (resultCode == Activity.RESULT_CANCELED) {
            JSONArray res = new JSONArray();
            this.callbackContext.success(res);
        } else {
            this.callbackContext.error("No images selected");
        }
    }
}

